package com.leetcode.题库;

/**
 * @author 覃国强
 * @date 2022-02-21 11:43
 */
public class 题库_0838_推多米诺 {

  static
  class Solution {
    public String pushDominoes(String dominoes) {
      if (dominoes == null || dominoes.length() < 2) {
        return dominoes;
      }

      char[] chars = dominoes.toCharArray();
      int[] leftRMinDistances = new int[chars.length];
      int[] rightLMinDistances = new int[chars.length];

      int leftRIndex = -1;
      for (int i = 0; i < chars.length; ++i) {
        if (chars[i] == 'R') {
          leftRIndex = i;
        }
        if (chars[i] == 'L') {
          leftRIndex = -1;
        }
        if (chars[i] == '.') {
          if (leftRIndex == -1) {
            leftRMinDistances[i] = Integer.MAX_VALUE;
          } else {
            leftRMinDistances[i] = i - leftRIndex;
          }
        }
      }

      int rightLIndex = -1;
      for (int i = chars.length - 1; i >= 0; --i) {
        if (chars[i] == 'L') {
          rightLIndex = i;
        }
        if (chars[i] == 'R') {
          rightLIndex = -1;
        }
        if (chars[i] == '.') {
          if (rightLIndex == -1) {
            rightLMinDistances[i] = Integer.MAX_VALUE;
          } else {
            rightLMinDistances[i] = rightLIndex - i;
          }
        }
      }

      for (int i = 0; i < chars.length; ++i) {
        if (chars[i] == '.') {
          if (leftRMinDistances[i] < rightLMinDistances[i]) {
            chars[i] = 'R';
          } else if (leftRMinDistances[i] > rightLMinDistances[i]) {
            chars[i] = 'L';
          }
        }
      }

      return new String(chars);
    }
  }

}
